package channel

import (
	"log"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
	ledgerApi "github.com/hyperledger/fabric-sdk-go/pkg/client/ledger"
	contextApi "github.com/hyperledger/fabric-sdk-go/pkg/common/providers/context"
	//gatewayApi "github.com/hyperledger/fabric-sdk-go/pkg/gateway"
)

const (
	channelID = "chl-01"
	//channelID   = "chl-11"
	chaincodeID = "econtract"
	orgID       = "Org1"
	userID      = "Admin"
)

type F_CHL_Summary_Info struct {
	BlockHeight      int
	TransactionCount int
	PeerCount        int
	ChaincodeCount   int
}

func GetSummaryInfo(channelProvider contextApi.ChannelProvider) (*F_CHL_Summary_Info, error) {
	var summary *F_CHL_Summary_Info

	summary = new(F_CHL_Summary_Info)
	client, err := ledger.New(channelProvider)
	if err != nil {
		log.Fatalf("-X-> 创建sdk客户端失败: %v\n", err)
		return nil, err
	}

	info, err := client.QueryInfo()
	if err != nil {
		log.Fatalf("-X-> 查询区块链概况失败: %v\n", err)
		return nil, err
	}

	//fmt.Printf("  |---> 接入点: \n%v\n", info.BCI)
	//fmt.Printf("---> info:\n%#+v\n", info)

	//fmt.Printf("区块高度:\n%v\n", info.BCI.Height)
	//fmt.Printf("当前区块Hash:\n%v\n", hex.EncodeToString(info.BCI.CurrentBlockHash))
	//fmt.Printf("前一区块Hash:\n%v\n", hex.EncodeToString(info.BCI.PreviousBlockHash))

	summary.BlockHeight = int(info.BCI.Height)
	summary.TransactionCount, _ = GetTotalTxCount(client, summary.BlockHeight)
	return summary, nil
}

func GetTxCount(client *ledgerApi.Client, blockNumber int) (int, error) {
	var n int

	// 根据区块查询交易
	block, err := client.QueryBlock(uint64(blockNumber))
	if err != nil {
		log.Fatalf("-X-> 查询区块失败: %v\n", err)
		return n, err
	}

	n = len(block.Data.Data)
	//fmt.Printf("  |---> 区块[%d]交易个数:  %d\n", blockNumber, n)

	return n, nil
}

func GetTotalTxCount(client *ledgerApi.Client, height int) (int, error) {
	var n int

	count := height - 1
	for i := 0; i <= count; i++ {
		txcount, _ := GetTxCount(client, i)
		n += txcount
	}

	return n, nil
}
